# @Time : 2020/7/30 14:30
# @Author : Fioman 
# @Phone : 13149920693
import cv2 as cv
import numpy as np

"""
函数cv.minAreaRect()能够绘制轮廓的最小包围矩形框,其语法格式是:
retval = cv.minAreaRect(points)
该值的结果是:
最小外接矩形的中心(x,y),(宽高),(旋转角度)
retval可以起名为boxInfo
然后boxInfo可以通过cv.boxPoints(boxInfo)转换为cv.drawContours()的结构要求.
"""
img = cv.imread("cc.bmp")
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

cv.imshow("Original", img)
T, thres = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)
image, contours, hierarchy = cv.findContours(thres, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)

rect = cv.minAreaRect(contours[0])
print("rect = {}".format(rect))
rectPoints = cv.boxPoints(rect)
rectPoints = np.int0(rectPoints)  # 取整
cv.drawContours(img,[rectPoints],-1,(0,255,0),1)

cv.imshow("MinRect",img)
cv.waitKey(0)
cv.destroyAllWindows()